<template>
  <div class="customer-box" ref="clueBoxRef">
    <CrmTitle
      pageType="customer"
      :moduleOption="moduleOption"
      @getModuleClueData="getModuleClueData"
      @setIsExpand="setIsExpand"
      :isExpand="isExpand"
      @setIsFilterShow="setIsFilterShow"
      :isFilterShow="isFilterShow"
      @setTableH="setTableH"
      @calculateTable="calculateTable"
      @sceneTypeSearch="sceneTypeSearch"
      @paramsSearch="paramsSearch"
      @threeSearch="threeSearch"
      @importValue="importValue"
      :exportLoading="exportLoading"
    />
    <CrmTable
      ref="crmTableRef"
      pageType="customer"
      :list="list"
      :loading="loading"
      :moduleOption="moduleOption"
      :meterHeaderList="meterHeaderList"
      :total="total"
      :pageNo="queryParams.pageNo"
      :pageSize="queryParams.pageSize"
      :domHeight="domHeight"
      @pageNextProver="pageNextProver"
      :setTimes="setTimes"
      @ordinaryOrAdvancedRequest="ordinaryOrAdvancedRequest"
      @handleDefault="handleDefault"
      @saveTableSort="saveTableSort"
      @sortChange="sortChange"
      @setLoading="setLoading"
    />
    <CustomerImportForm ref="importFormRef" @success="ordinaryOrAdvancedRequest" />
  </div>
</template>
<script setup>
import * as TableSort from '@/utils/sortTable'
import * as CrmModuleApi from '@/api/crm/module'
import * as AdvancedQueryApi from '@/api/crm/advancedQuery/index.ts'
import * as CustomerApi from '@/api/crm/customer'
import { customFieldHeadList } from '@/api/crm/module/index'
import download from '@/utils/download'
import { emitter } from '@/utils/eventBus.ts'

import CrmTitle from '@/views/crm/components/CrmTitle/index.vue'
import CrmTable from '@/views/crm/components/CrmTable/index.vue'
import CustomerImportForm from './CustomerImportForm.vue'

defineOptions({ name: 'CrmCustomer' })

const isExpand = ref(true)
const isFilterShow = ref(0)
const moduleOption = ref([])
const loading = ref(false)
const list = ref([])
const total = ref(0)
const setTimes = ref({})
const meterHeaderList = ref()
const clueBoxRef = ref(null)
const domHeight = ref(0)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  moduleId: '',
  sceneType: '',
  sortStr: '',
  name: null,
  transformStatus: false,
  telephone: null,
  mobile: null,
  sortFields: {}
})
const crmTableRef = ref(null)
const ordinaryOrAdvanced = ref(0) //0 普通  1 高级
const paramsValue = ref({})
/**当前高级筛选是展开还是收起*/
const expandOrColl = computed(() => {
  return isExpand.value && isFilterShow.value
})
/**设置表格的高度*/
const setTableH = (val) => {
  crmTableRef.value?.setTableHeight(val)
}
const oldHeight = ref(0)
/**拿到title高度计算表格的高度*/
const calculateTable = (val) => {
  oldHeight.value = domHeight.value - val
  setTableH(domHeight.value - val)
}
/**设置外露值的长度*/
const setIsFilterShow = (val) => {
  isFilterShow.value = val
  if (val == 0) {
    setTableH(domHeight.value)
  }
}
/**展开、收起高级筛选*/
const setIsExpand = () => {
  isExpand.value = !isExpand.value
  if (isExpand.value) {
    setTableH(oldHeight.value)
  } else {
    setTableH(domHeight.value)
  }
}
/**根据模块筛选*/
const getModuleClueData = (val) => {
  queryParams.moduleId = val
  getCustomerList()
}
/**分页*/
const pageNextProver = (val) => {
  const { page, limit } = val
  queryParams.pageNo = page
  queryParams.pageSize = limit
  ordinaryOrAdvancedRequest()
}
/**负责的请求*/
const sceneTypeSearch = (val) => {
  queryParams.sceneType = val
  queryParams.pageNo = 1
  ordinaryOrAdvanced.value = 0
  ordinaryOrAdvancedRequest()
}
/**高级筛选*/
const paramsSearch = (params) => {
  paramsValue.value = params
  queryParams.pageNo = 1
  ordinaryOrAdvanced.value = 1
  ordinaryOrAdvancedRequest()
}
const checkStringType = (str) => {
  // 正则表达式
  const nameReg = /^[\u4e00-\u9fa5a-zA-Z\s\.]+$/
  const phoneReg = /^1[3-9]\d{9}$/
  const telReg = /^\d{3,4}-\d{7,8}$/

  if (nameReg.test(str)) {
    return 0
  } else if (phoneReg.test(str)) {
    return 1
  } else if (telReg.test(str)) {
    return 1
  } else {
    return 0
  }
}
const typeMap = {
  0: 'name',
  1: 'mobile',
  2: 'telephone'
}
const setLoading = (val) => {
  loading.value = val
}
// 三和一的筛选
const threeSearch = (val) => {
  queryParams.name = null
  queryParams.telephone = null
  queryParams.mobile = null
  if (val) {
    queryParams[typeMap[checkStringType(val)]] = val
  }
  queryParams.pageNo = 1
  ordinaryOrAdvanced.value = 0
  ordinaryOrAdvancedRequest()
}
/**高级搜索*/
const getCustomerListAdvance = async () => {
  let data
  const obj = {
    pageNo: queryParams.pageNo,
    pageSize: queryParams.pageSize,
    params: paramsValue.value
  }
  // 排序
  if (Object.keys(queryParams.sortFields).length > 0) {
    obj.sortStr = JSON.stringify(queryParams.sortFields)
  }
  try {
    loading.value = true
    data = await AdvancedQueryApi.customerAdvancePage(obj)

    const ids = data.list.map((item) => item.id)
    if (ids.length) {
      const results = await CustomerApi.getCustomerTag({ ids: ids })
      if (Object.keys(results).length) {
        list.value = mergeValues(data.list, results)
      } else {
        data.list.forEach((item) => {
          item.labelList = []
        })
        list.value = data.list
      }
    } else {
      data.list.forEach((item) => {
        item.labelList = []
      })
      list.value = data.list
    }

    total.value = data.total
  } finally {
    loading.value = false
  }
}
/**合并数据*/
const mergeValues = (arrayA, objectB) => {
  arrayA.forEach((itemA) => {
    let key = itemA.id
    if (objectB[key]) {
      itemA.labelList = []
      Object.assign(itemA.labelList, objectB[key])
    }
  })
  return arrayA
}
/**普通搜索线索列表**/
const getCustomerList = async () => {
  let data
  // 排序
  if (Object.keys(queryParams.sortFields).length > 0) {
    queryParams.sortStr = JSON.stringify(queryParams.sortFields)
  }
  try {
    loading.value = true
    data = await CustomerApi.getCustomerPage(queryParams)

    const ids = data.list.map((item) => item.id)
    if (ids.length) {
      const results = await CustomerApi.getCustomerTag({ ids: ids })
      if (Object.keys(results).length) {
        list.value = mergeValues(data.list, results)
      } else {
        data.list.forEach((item) => {
          item.labelList = []
        })
        list.value = data.list
      }
    } else {
      data.list.forEach((item) => {
        item.labelList = []
      })
      list.value = data.list
    }
    total.value = data.total
  } finally {
    loading.value = false
  }
}
emitter.on('refreshCustomer', () => {
  ordinaryOrAdvancedRequest()
})
// 普通请求 还是高级请求
const ordinaryOrAdvancedRequest = () => {
  if (ordinaryOrAdvanced.value) {
    getCustomerListAdvance()
  } else {
    getCustomerList()
  }
}
/**表头 + 自定义字段表头*/
const getFiledList = async () => {
  const fileValue = await customFieldHeadList({
    moduleId: queryParams.moduleId,
    tableType: '2'
  })
  let arr = []
  fileValue.map((item, index) => {
    arr.push({
      isflod: false,
      label: item.name,
      prop: item.fieldName,
      show: item.isShow == 0 ? false : true,
      sort: index + 5,
      width: '120'
    })
    if (item.fieldType == 'time') {
      setTimes.value[item.fieldName] = item.fieldName
    }
  })
  const tableSort = TableSort.getMeterList(TableSort.DICT.CUSTOMER)
  meterHeaderList.value = [...tableSort, ...arr].reduce((acc, current) => {
    if (!acc.find((item) => item.label === current.label)) {
      acc.push(current)
    }
    return acc
  }, [])
}
/** 恢复默认 */
const handleDefault = () => {
  getFiledList()
}
/** 保存table配置 */
const saveTableSort = () => {
  TableSort.setMeterList(TableSort.DICT.CUSTOMER, meterHeaderList.value)
}
const importFormRef = ref(null)
const exportLoading = ref(false)
const message = useMessage()
/**导入*/
const importValue = async (val) => {
  if (val == 'import') {
    importFormRef.value?.open()
  } else {
    try {
      // 导出的二次确认
      await message.exportConfirm()
      // 发起导出
      exportLoading.value = true
      const data = await CustomerApi.exportCustomerNew(queryParams)
      download.excel(data, '客户.xls')
    } catch {
    } finally {
      exportLoading.value = false
    }
  }
}
/**获取模块*/
const getModule = async () => {
  moduleOption.value = await CrmModuleApi.getModuleList()
}
onMounted(() => {
  domHeight.value = clueBoxRef.value.offsetHeight - 160
  getModule()
  queryParams.sceneType = 4
  getCustomerList()
  getFiledList()
})
/**排序*/
const sortChange = (key, val) => {
  queryParams.sortFields[key] = val
  ordinaryOrAdvancedRequest()
}
</script>

<style scoped lang="scss">
.customer-box {
  width: 100%;
  flex-grow: 1;
}
</style>
